package com.xiaoma.lock.myreentrancelock;

/**
 * 可重入锁
 * Created by Fant.J.
 * 2018/3/6 20:12
 */
public class MyLock{
    
    // 声明一个判断锁的布尔值
    private boolean isLocked = false;
    
    Thread lockBy = null;
    
    int lockCount = 0;
    
    public synchronized void lock(){
        
        Thread currentThread = Thread.currentThread(); // 获取到当前线程
        while(isLocked && currentThread != lockBy){
            try{
                // 锁为当前调用该方法的对象
                wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        isLocked = true;
        lockBy = currentThread; // 将currentThread线程指向 lockBy线程
        lockCount++;// 计数器自增
        
    }
    
    public synchronized void unlock(){
        if(lockBy == Thread.currentThread()){
            lockCount--;
            if(lockCount == 0){
                notify();
                isLocked = false;
            }
        }
    }
    
}
